package com.marktotop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.marktotop.mapper.OrderMapper;
import com.marktotop.pojo.Order;
import com.marktotop.pojo.SeckillGoods;
import com.marktotop.pojo.SeckillOrder;
import com.marktotop.pojo.User;
import com.marktotop.service.IOrderService;
import com.marktotop.service.ISeckillGoodsService;
import com.marktotop.service.ISeckillOrderService;
import com.marktotop.vo.GoodsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author MarkToTop
 * @since 2021-06-18
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private ISeckillGoodsService seckillGoodsService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ISeckillOrderService seckillOrderService;
    /**
     * 秒杀下单
     *      减库存
     *      创建订单
     *      生成秒杀订单
     *
     * @param user
     * @param goods
     * @return
     */
    @Override
    public Order seckill(User user, GoodsVO goods) {
        // 秒杀商品表，减库存
        SeckillGoods seckillGoods = seckillGoodsService.getOne(new QueryWrapper<SeckillGoods>().eq("goods_id", goods.getId()));
        seckillGoods.setStokeCount(seckillGoods.getStokeCount() - 1);
        seckillGoodsService.updateById(seckillGoods);
        // 创建订单
        Order order = new Order()
                .setUserId(user.getId())
                .setGoodsId(goods.getId())
                .setDeliveryAddrId(0L)
                .setGoodsName(goods.getGoodsName())
                .setGoodsCount(1)
                .setGoodsPrice(seckillGoods.getSeckillPrice())
                .setOrderChannel(1)
                .setStatus(0)
                .setCreateTime(new Date());
        orderMapper.insert(order);
        // 生成秒杀订单
        SeckillOrder seckillOrder = new SeckillOrder()
                .setUserId(user.getId())
                .setGoodsId(goods.getId())
                .setOrderId(order.getId());
        seckillOrderService.save(seckillOrder);

        return order;
    }
}
